package com.admin.common.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.admin.common.enums.EnumIstatus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

import com.admin.common.enums.EnumResult;
import com.admin.domain.AdminDO;
import com.admin.mapper.AdminMapper;
import com.admin.service.MenuService;

/**
 * 1.shiro是一套session管理、session缓存、登录缓存、权限缓存管理框架。只要继承一个AuthorizingRealm进行一些实现，额外加些配置，改动一下即可。底层数据源支持多种方式，如redis
 * 2.session缓存的key为，shiro_redis_session:shiro生成的token，value为SimpleSession对象
 * 3.登录缓存的key为，shiro_redis_cache:登录账号，value为SimpleAuthenticationInfo对象，该对象存了PrincipalCollection对象，所以进而可以获得权限缓存。
 * 4.权限缓存的key为，PrincipalCollection对象，value为权限信息
 * 
 * @author ZY
 * @date 2018/10/18
 */
public class UserRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // 对应该账号无权限缓存时，走此方法，查询权限。
        Integer userId = ShiroUtils.getUserId();
        MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
        List<String> menuPerms = menuService.getCanSeeMenuPerms(userId).getData();
        Set<String> perms = new HashSet<String>();
        if (CollectionUtils.isNotEmpty(menuPerms)) {
            for (String perm : menuPerms) {
                if (!StringUtils.isEmpty(perm)) {
                    perms.add(perm.trim());
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 对应账号无登录缓存时，走此方法，查询登录。（只在登录时可能会调用）
        String username = (String)token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        AdminMapper adminMapper = ApplicationContextRegister.getBean(AdminMapper.class);
        // 查询用户信息
        AdminDO adminDO = adminMapper.selectByUsername(username);

        // 账号不存在
        if (adminDO == null) {
            throw new UnknownAccountException(EnumResult.DATA_NULL.getMsg());
        }
        // 密码错误
        if (!password.equals(adminDO.getPassword())) {
            throw new IncorrectCredentialsException(EnumResult.USER_LOGIN_PASSWORD_ERROR.getMsg());
        }
        // 账号锁定
        if (!EnumIstatus.OK.getKey().equals(adminDO.getIstatus())) {
            throw new LockedAccountException(EnumResult.USER_ISTATUS_NOT_OK.getMsg());
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(adminDO, password, getName());
        return info;
    }

    /**
     * 清除用户权限缓存、登录缓存（当前登录操作人）
     */
    public void clearCachedAuthorization() {
        clearCachedAuthorization(ShiroUtils.getUser().getUsername());
    }

    /**
     * 清除指定用户权限缓存、登录缓存（指定用户）
     */
    public void clearCachedAuthorization(String username) {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            // 用户名对应的登录缓存
            SimpleAuthenticationInfo info = (SimpleAuthenticationInfo)cache.get(username);
            if (info != null) {
                // 删除权限缓存
                cache.remove(info.getPrincipals());
                // 删除用户名对应的登录缓存
                cache.remove(username);
            }
        }
        // if (cache != null) {
        // // 用户名字符串的字节
        // for (Object key : cache.keys()) {
        // String keyStr = new String((byte[])key);
        // if (username.equals(keyStr.split(":")[1])) {
        // // 用户名对应的登录缓存
        // SimpleAuthenticationInfo info = (SimpleAuthenticationInfo)cache.get(username);
        // if (info != null) {
        // // 删除权限缓存
        // cache.remove(info.getPrincipals());
        // // 删除用户名对应的登录缓存
        // cache.remove(username);
        // }
        // }
        // }
        // }
    }

    /**
     * 清空所有人权限缓存
     */
    public void clearAllCachedAuthorization() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            // 用户名字符串的字节
            for (Object key : cache.keys()) {
                String keyStr = new String((byte[])key);
                // 用户名对应的登录缓存
                SimpleAuthenticationInfo info = (SimpleAuthenticationInfo)cache.get(keyStr.split(":")[1]);
                if (info != null) {
                    // 删除权限缓存
                    cache.remove(info.getPrincipals());
                }
            }
        }
    }

}
